/*
 * @Author: liuying 247220246@qq.com
 * @Date: 2024-12-20 17:52:41
 * @LastEditors: liuying 247220246@qq.com
 * @LastEditTime: 2024-12-26 15:07:38
 * @FilePath: \my-book-react\src\hooks\useRequest\useRequest.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import useSWR, { SWRConfiguration, SWRResponse } from 'swr';
import { AxiosRequestConfig, AxiosError } from 'axios';
import axiosInstance from '@/hooks/useRequest/axiosInstance';
interface Response<Data> {
  code: number;
  data: Data;
  msg: string;
}
interface useRequestResponse<Data, Error>
  extends Pick<SWRResponse<Response<Data>, AxiosError<Error>>, 'isValidating' | 'error' | 'mutate'> {
  data: Data | undefined;
  response: Response<Data> | undefined;
}
function useRequest<Data = unknown, Error = unknown>(
  request: AxiosRequestConfig,
  config?: SWRConfiguration
): useRequestResponse<Data, Error> {
  // Ensure request.url is defined
  // const url = request.url || '';

  // // Define the fetcher function
  // const fetcher = () => axiosInstance.request<Data>({ ...request, url });
  // const response: SWRResponse<Data, AxiosError<Error>> = useSWR<Data, AxiosError<Error>>(url, fetcher, config);

  // return response;
  const {
    data: response,
    error,
    mutate,
    isValidating,
  } = useSWR<Response<Data>, AxiosError<Error>>(request.url, () => axiosInstance.request(request), config);
  return {
    data: response?.data,
    response,
    error,
    mutate,
    isValidating,
  };
}
export default useRequest;
